package org.cocos2dx.javascript;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.games.AnnotatedData;
import com.google.android.gms.games.EventsClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.event.Event;
import com.google.android.gms.games.event.EventBuffer;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

public class EventManager {

    private static EventManager mInstance = null;

    public static EventManager getInstance() {
        if (null == mInstance) {
            mInstance = new EventManager();
        }
        return mInstance;
    }

    private EventsClient mEventsClient;
    private static final String TAG = "EventManager";

    public void init(InstantAppActivity context, GoogleSignInAccount googleSignInAccount) {
        Log.d(TAG, "init");
        mEventsClient = Games.getEventsClient(context, googleSignInAccount);
        //loadAndPrintEvents();
    }

    private void loadAndPrintEvents() {

        mEventsClient.load(true)
                .addOnSuccessListener(new OnSuccessListener<AnnotatedData<EventBuffer>>() {
                    @Override
                    public void onSuccess(AnnotatedData<EventBuffer> eventBufferAnnotatedData) {
                        EventBuffer eventBuffer = eventBufferAnnotatedData.get();

                        int count = 0;
                        if (eventBuffer != null) {
                            count = eventBuffer.getCount();
                        }

                        Log.i(TAG, "number of events: " + count);

                        for (int i = 0; i < count; i++) {
                            Event event = eventBuffer.get(i);
                            Log.i(TAG, "event: "
                                    + event.getName()
                                    + " -> "
                                    + event.getValue());
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, e.toString());
                    }
                });
    }

    public void increment(String param) {
        mEventsClient.increment(param, 1);
    }
}
